package de.le.mfw.client.main.presenter;

import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.mvp4g.client.annotation.Presenter;
import com.mvp4g.client.presenter.BasePresenter;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.events.HasClickHandlers;

import de.le.mfw.client.main.MainEventBus;
import de.le.mfw.client.main.service.UserServiceAsync;
import de.le.mfw.client.main.view.SettingsViewImpl;
import de.le.mfw.client.util.LoadingScreenCallback;
import de.le.mfw.shared.UserDTO;

@Presenter(view = SettingsViewImpl.class)
public class SettingsPresenter extends
		BasePresenter<SettingsViewImpl, MainEventBus> {

	public interface SettingsView extends IsWidget {
		public HasClickHandlers getSaveButton();

		public boolean isValid();

		public String getEmail();

		public void setEmail(String email);

		public String getPassword();
	}

	@Inject
	private UserServiceAsync userService;

	private UserDTO user = null;

	@Override
	public void bind() {
		view.getSaveButton().addClickHandler(new SaveClickHandler());
	}

	public void onGoToSetting(UserDTO user) {
		this.user = user;
		Widget widget = view.asWidget();
		view.setEmail(user.getEmail());
		eventBus.setContentWidget(widget);
	}

	private final class SaveClickHandler implements ClickHandler {
		public void onClick(ClickEvent event) {
			if (view.isValid()) {
				String email = view.getEmail();
				String password = view.getPassword();
				if (email != null && !email.isEmpty()
						&& !email.equals(user.getEmail())) {
					userService.changeEmail(user, email,
							new LoadingScreenCallback<Void>(event) {

								@Override
								protected void success(Void result) {
								}
							});
				}
				if (password != null && !password.isEmpty()) {
					userService.changePassword(user, password,
							new LoadingScreenCallback<Void>(event) {

								@Override
								protected void success(Void result) {
								}
							});
				}
			}
		}
	}

}
